﻿using System.Security.Cryptography;
using System.Text;
using NewLife;
using OpenAiClient.Util.GZip;

namespace OpenAiClient.Util.Security
{
    public static class SafeDataHelper
    {
        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="value">待加密的字符串</param>
        /// <param name="encryptKey">加密密钥</param>
        /// <returns>加密成功返回加密后的字符串,失败返回空</returns>
        public static string Encrypt(string value, string encryptKey)
        {
            if (string.IsNullOrWhiteSpace(value) || encryptKey == null)
            {
                return string.Empty;
            }

            var zippedData = GZipHelper.GZipCompressString(value);
            var buffer = Aes.Create().Encrypt(zippedData.GetBytes(Encoding.UTF8), encryptKey.GetBytes());
            return buffer.ToBase64();
        }

        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="value">待解密的字符串</param>
        /// <param name="decryptKey">解密密钥</param>
        /// <returns>解密成功返回解密后的字符串,失败返回空</returns>
        public static string Decrypt(string value, string decryptKey)
        {
            if (string.IsNullOrWhiteSpace(value) || decryptKey == null)
            {
                return string.Empty;
            }

            var buffer = Aes.Create().Decrypt(value.ToBase64(), decryptKey.GetBytes());
            var zippedData = buffer.ToStr(Encoding.UTF8);
            return GZipHelper.GZipDecompressString(zippedData);
        }
    }
}
